import { login } from '@/api/login'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, uuid).then(res => {
            setToken(res.data.accesstoken);
            setUserInfo(res.data)
            this.token = res.data.accesstoken;
            resolve();
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          try {
            const user = getUserInfo()
            const avatar = '/src/assets/images/profile.jpg';
            
            if (user.roleCodes && user.roleCodes.length > 0) { // 验证返回的roles是否是一个非空数组
              // this.roles = user.roleCodes
              // this.permissions = user.permissionCodes
              this.roles = ["admin"];
              this.permissions = ["*:*:*"]
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.roles = ["admin"];
            this.permissions = ["*:*:*"]
            this.name = user.userName
            this.avatar = avatar;
            resolve(user)
          } catch (error) {
            reject(error)
          }
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          try {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          } catch (error) {
            reject(error)
          }
        })
      }
    }
  })

export default useUserStore
